package com.xjh.him.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class PinyinUtil {

    /**
     * 获取字符串的首字母，包括汉字
     * @param str
     * @return
     */
    public static String getFirstChar(String str) {
        char[] charArray = str.toCharArray();
        HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();
        outputFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

        StringBuilder builder = new StringBuilder();
        for (char ch : charArray) {
            if (ch > 128) {
                try {
                    String[] array = PinyinHelper.toHanyuPinyinStringArray(ch, outputFormat);
                    if (array == null) {
                        return "A";
                    }
                    builder.append(array[0]);
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            }else {
                builder.append(ch);
            }
        }
        String convertStr = builder.toString().toUpperCase();
        return convertStr.length() > 0 ? convertStr.substring(0, 1) : "";
    }
}
